/**
 * MIT License
 * Copyright (c) 2018 yadong.zhang
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.xuyiwei.xblog.modular.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.xuyiwei.xblog.business.article.model.Comment;
import com.xuyiwei.xblog.business.article.result.article.input.CommentConditionVO;
import com.xuyiwei.xblog.business.article.result.article.out.CommentDto;
import com.xuyiwei.xblog.business.article.service.IArticleService;
import com.xuyiwei.xblog.business.article.service.ICommentService;
import com.xuyiwei.xblog.business.system.model.Notice;
import com.xuyiwei.xblog.business.system.model.User;
import com.xuyiwei.xblog.business.system.result.user.input.UserParam;
import com.xuyiwei.xblog.business.system.result.user.input.UserRegister;
import com.xuyiwei.xblog.business.system.service.IMailService;
import com.xuyiwei.xblog.business.system.service.INoticeService;
import com.xuyiwei.xblog.business.system.service.IUserService;
import com.xuyiwei.xblog.core.base.constant.enums.CommentStatusEnum;
import com.xuyiwei.xblog.core.base.constant.enums.CommonStatusEnum;
import com.xuyiwei.xblog.core.base.controller.BaseController;
import com.xuyiwei.xblog.core.base.response.Result;
import com.xuyiwei.xblog.core.common.constant.factory.PageFactory;
import com.xuyiwei.xblog.core.exception.BizExceptionEnum;
import com.xuyiwei.xblog.core.exception.GunsException;
import com.xuyiwei.xblog.core.shiro.ShiroKit;
import com.xuyiwei.xblog.core.shiro.ShiroUser;
import com.xuyiwei.xblog.core.util.OssUtil;
import com.xuyiwei.xblog.core.util.QQUtil;
import com.xuyiwei.xblog.core.util.RSAUtil;
import com.xuyiwei.xblog.core.util.RestClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import sun.nio.cs.US_ASCII;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 网站接口类，申请友链、评论、点赞等
 *
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @website https://www.zhyd.me
 * @date 2018/4/18 11:48
 * @since 1.0
 */
@RestController
@RequestMapping("/api")
public class RestApiController extends BaseController {

    @Autowired
    private INoticeService noticeService;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private IMailService mailService;

    @Autowired
    private IUserService userService;

    @PostMapping("/listNotice")
    @ResponseBody
    public Result<List<Notice>> listNotice() {
        Result<List<Notice>> result = Result.instance();
        try{
            EntityWrapper<Notice> wrapper = new EntityWrapper<>();
            wrapper.eq("status", CommonStatusEnum.USE.getKey());
            List<Notice> list = noticeService.selectList(wrapper);
            result.setData(list);
        }catch (Exception e){
            result.setError("500","查询通知列表错误");
        }
        return result;
    }

    @PostMapping("/doPraise/{id}")
    public Result<Boolean> doPraise(@PathVariable("id") Long id) {
        Result<Boolean> result = Result.instance();
        try {
            articleService.doPraise(id);
            result.setData(true);
        } catch (GunsException e) {
            result.setError("500",e.getMessage());
        }
        return result;
    }

    @PostMapping("/doOppose/{id}")
    public Result<Boolean> doOppose(@PathVariable("id") Long id) {
        Result<Boolean> result = Result.instance();
        try {
            articleService.doOppose(id);
            result.setData(true);
        } catch (GunsException e) {
            result.setError("500",e.getMessage());
        }
        return result;
    }

    @PostMapping("comments")
    public Result<List<CommentDto>> comments(CommentConditionVO vo) {
        Result<List<CommentDto>> result = Result.instance();
        try{
            Page<CommentDto> page = new PageFactory<CommentDto>().defaultPage();
            vo.setStatus(CommentStatusEnum.APPROVED.getKey());
            List<CommentDto> list = commentService.findPageByCondition(page,vo,page.getOrderByField(),page.isAsc());

            result.setData(list);
        }catch (Exception e){
            result.setError("500",e.getMessage());
        }
        return result;
    }

    @PostMapping("comment")
    public Result<Boolean> comment(Long pid,String content,Long sid) {
        Result<Boolean> result = Result.instance();
        try {
            ShiroUser user = ShiroKit.getUser();
            if(user!=null){
                Comment comment = new Comment();
                comment.setContent(content);
                comment.setPid(pid);
                comment.setSid(sid);
                comment.setQq(user.getQq());
                comment.setNickname(user.getNickName());
                comment.setEmail(user.getEmail());
                comment.setAvatar(user.getAvatar());
                commentService.comment(comment);
            }else{
                result.setError("500","登录用户信息已过期，请重新登录");
            }
        } catch (Exception e) {
            result.setError("500",e.getMessage());
        }
        return result;
    }

    /**
     * 发送邮箱验证码
     * @param email
     * @return
     */
    @PostMapping("sendEmailCode")
    public Result<Boolean> sendEmailCode(String email) {
        Result<Boolean> result = Result.instance();
        try {
            mailService.sendEmailCode(email);
        } catch (Exception e) {
            result.setError("500",e.getMessage());
        }
        return result;
    }

    /**
     * 获取前端加密的公匙
     * @return
     */
    @PostMapping("generateBase64PublicKey")
    public Result<String> generateBase64PublicKey() {
        Result<String> result = Result.instance();
        try {
            String publicKey = RSAUtil.generateBase64PublicKey();
            result.setData(publicKey);
        } catch (Exception e) {
            result.setError("500",e.getMessage());
        }
        return result;
    }

    /**
     * 验证邮件验证码
     * @return
     */
    @PostMapping("verifyCode")
    public Result<Boolean> verifyCode(String email,String code) {
        Result<Boolean> result = Result.instance();
        try {
            boolean isPass = mailService.verifyCode(email,code);
            result.setData(isPass);
        } catch (Exception e) {
            result.setError("500",e.getMessage());
        }
        return result;
    }

    @PostMapping("/qq/{qq}")
    public Result<Map<String, String> > qq(@PathVariable("qq") String qq) {
        Result<Map<String, String> > result = Result.instance();
        try{
            if (StringUtils.isEmpty(qq)) {
                return  result.setError("500","QQ号不能为空");
            }
            result.setData(QQUtil.getQQInfo(qq));
        }catch (Exception e){
            return  result.setError("500","实时获取QQ信息异常");
        }

        return result;
    }

}
